package com.wxq.workpad.upgradation;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;


import androidx.core.content.FileProvider;

import com.wxq.workpad.R;
import com.wxq.workpad.utils.DeviceUtils;

import java.io.File;

/**
 * 功能详细描述
 *
 * @author xyx on 2017/8/15
 * @e-mail 384744573@qq.com
 * @see [相关类/方法](可选)
 */

public class DownloadDialog extends Dialog implements View.OnClickListener {
    private static final String APK_INSTALL = "去安装";
    private static final String APK_DOWNLOAD = "下载更新";
    private TextView btn_open;
    private ImageView iv_close;
    private TextView tv_content;
    private ImageView iv_top;

    private Context mContext;
    private String apkInstallPath;
    private String updateUrl = "";
    private DownloadListener listener;

    public DownloadDialog(Context context) {
        super(context, R.style.DialogTheme);
        mContext = context;

        View mContentView = LayoutInflater.from(mContext).inflate(R.layout.dialog_download, null);
        setContentView(mContentView);

        Window window = getWindow();
        window.setGravity(Gravity.CENTER);  //此处可以设置dialog显示的位置
        window.setLayout(DeviceUtils.dp2px(mContext, 310), ViewGroup.LayoutParams.WRAP_CONTENT); //设置宽高,这样设置才有效

        initView(mContentView);

    }


    private void initView(View mContentView) {
        btn_open = mContentView.findViewById(R.id.btn_open);
        iv_close = mContentView.findViewById(R.id.iv_close);
        tv_content = mContentView.findViewById(R.id.tv_content);
        iv_top = mContentView.findViewById(R.id.iv_top);
//        iv_top.setColorFilter(ConfigHelper.getColorMainInt(mContext));

        btn_open.setOnClickListener(this);
        iv_close.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_open:
                if (btn_open.getText().toString().equals(APK_INSTALL)) {
                    try {
                        jumpInstall(mContext,new File(apkInstallPath));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else if (btn_open.getText().toString().equals(APK_DOWNLOAD)) {
                    try {
                        if (!TextUtils.isEmpty(updateUrl)) {
                            //包含.apk则下载该文件，不包含则打开浏览器跳转链接下载
                            if (updateUrl.contains(".apk")) {
                                if (listener != null) {
                                    listener.downloadApk();
                                }
                            } else {
                                Uri uri = Uri.parse("" + updateUrl);
                                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                                if (null != intent.resolveActivity(mContext.getPackageManager())) {
                                    mContext.startActivity(intent);
                                }
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                if (listener != null) {
                    listener.isNeedDissmiss();
                }
                break;
            case R.id.iv_close:
                dismiss();
                break;
            default:
                break;
        }
    }

    /**
     * 去安装
     *
     * @param content 内容
     * @param apkPath 安装地址
     */
    public void showInstallDialog(String content, String apkPath) {
        this.apkInstallPath = apkPath;
        if (!TextUtils.isEmpty(content)) {
            tv_content.setText(content);
        }
        btn_open.setText(APK_INSTALL);
        setCanceledOnTouchOutside(false);
        show();
    }

    /**
     * 下载更新
     *
     * @param content   内容
     * @param updateUrl 升级地址
     */
    public void showDownloadDialog(String content, String updateUrl) {
        this.updateUrl = updateUrl;
        if (!TextUtils.isEmpty(content)) {
            tv_content.setText(content);
        }
        btn_open.setText(APK_DOWNLOAD);
        setCanceledOnTouchOutside(false);
        show();
    }

    /**
     * 隐藏关闭按钮，对应app版本号低强制升级的情况
     *
     * @param content 强制升级提醒文案
     */
    public void disappearClose(String content) {
        iv_close.setVisibility(View.GONE);
        if (!TextUtils.isEmpty(content)) {
            tv_content.setText(content);
        } else {
            tv_content.setText("当前版本太低啦，您需要升级至最新版本才能继续使用。");
        }
        setCanceledOnTouchOutside(false);
    }

    public void setBtnTxt(String btnTxt) {
        if (!TextUtils.isEmpty(btnTxt)) {
            btn_open.setText(btnTxt);
        }
    }

    public void setListener(DownloadListener listener) {
        this.listener = listener;
    }

    public interface DownloadListener {
        /**
         * app内下载Apk文件
         */
        void downloadApk();

        /**
         * 点击 下载/安装 按钮后是否需要关闭dialog
         */
        void isNeedDissmiss();
    }
    public static void jumpInstall(Context mContext, File apkFile) {
        try {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            //兼容7.0
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                String provider = mContext.getPackageName() + ".fileprovider";
                Uri contentUri = FileProvider.getUriForFile(mContext, provider, apkFile);
                intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
            } else {
                intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            }
            openInstall(mContext, intent);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static void installApk(Context context, String apkFilePath) {
        File apkFile = new File(apkFilePath);
        if (!apkFile.exists()) {
            return;
        }
        Uri apkUri = Uri.fromFile(apkFile);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(intent);
    }


    private static void openInstall(Context context, Intent intent) {
        if (context.getPackageManager().queryIntentActivities(intent, 0).size() > 0) {
            // 或者startActivityForResult(intent, 10086);然后在相应页面接收回调处理安装
            context.startActivity(intent);
        }
    }
}
